package com.meida.paotui.app.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.meida.common.base.handler.PayInfoHandler;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.DateUtils;
import com.meida.module.pay.client.entity.PayInfo;
import com.meida.module.pay.provider.handler.PaySuccessHandler;
import com.meida.module.pay.provider.service.PayInfoService;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import com.meida.paotui.bus.client.entity.BusCustomerdetail;
import com.meida.paotui.bus.client.entity.BusGoodsorder;
import com.meida.paotui.bus.provider.service.BusCustomerdetailService;
import com.meida.paotui.bus.provider.service.impl.BusGoodsorderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 订单购买处理器
 *
 * @author zyf
 */
@Component("orderPayHandler")
public class OrderPayHandler implements PayInfoHandler, PaySuccessHandler {

    @Autowired
    private PayInfoService payInfoService;


    @Autowired
    private AppUserService userService;

    @Autowired
    private BusGoodsorderServiceImpl busGoodsorderService;

    @Autowired
    private BusCustomerdetailService busCustomerdetailService;


    @Override
    public ResultBody validate(CriteriaSave cs, EntityMap requestMap) {
        Long companyId = OpenHelper.getCompanyId();
        Long userId = OpenHelper.getUserId();
        AppUser user = userService.getById(userId);
        String userType = user.getUserType();
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaSave cs, EntityMap params) {
    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, Object object) {

    }

    /**
     * 创建支付信息
     *
     * @param cs         对象模型
     * @param requestMap 参数接收
     * @param outTradeNo 订单号
     * @return
     */
    @Override
    public Object getPayInfo(CriteriaSave cs, EntityMap requestMap, String outTradeNo) {
        PayInfo payInfo = cs.getEntity(PayInfo.class);
        ApiAssert.isNotEmpty("订单号不能为空", outTradeNo);
        BusGoodsorder goodsorder = busGoodsorderService.getById(outTradeNo);
        payInfo.setOrderBody("订单支付");
        payInfo.setOrderTitle("订单支付");
        payInfo.setOrderAmount(goodsorder.getRealPaySum());
        payInfo.setOutTradeNo(outTradeNo);
        return payInfo;
    }

    /**
     * 订单回调检验
     *
     * @param payMessage 支付回调消息
     * @param context    上下文参数,可传递到success方法内
     * @param payService 支付服务
     * @param outTradeNo 订单号
     * @return
     */
    @Override
    public boolean validate(PayMessage payMessage, Map<String, Object> context, PayService payService, String outTradeNo) {
        return payInfoService.validate(outTradeNo);
    }


    /**
     * 订单回调业务处理
     *
     * @param payMessage 支付回调消息
     * @param outTradeNo 订单号
     * @param context    上下文参数
     * @param payService 支付服务
     * @return
     */
    @Override
    public boolean success(PayMessage payMessage, String outTradeNo, Map<String, Object> context, PayService payService) {
        System.out.print("========================================订单支付回调======================================");
        //获取创建订单时参数
        PayInfo info =payInfoService.findByOutTradeNo(outTradeNo);
        BusGoodsorder goodsorder = busGoodsorderService.getById(outTradeNo);
        //使用的有优惠券的情况
        if(ObjectUtils.isNotEmpty(goodsorder.getCouponId())){
            QueryWrapper<BusCustomerdetail> sd=new QueryWrapper();
            sd.eq("customerId",goodsorder.getCouponId());
            sd.eq("userId",info.getUserId());
            BusCustomerdetail customerdetail=busCustomerdetailService.getOne(sd);
            if(ObjectUtils.isNotEmpty(customerdetail)&&customerdetail.getCoupCount()>0){
                //优惠券减一
                customerdetail.setCoupCount(customerdetail.getCoupCount()-1);
                busCustomerdetailService.saveOrUpdate(customerdetail);
            }
            if(ObjectUtils.isNotEmpty(customerdetail)&&customerdetail.getCoupCount()==0){
                busCustomerdetailService.removeById(customerdetail.getCustomerdetailId());
            }
        }
        goodsorder.setStatus(1);//支付成功状态为1
        goodsorder.setPayType(payMessage.getPayType());
        goodsorder.setPayTime(DateUtils.getDateTime());
        busGoodsorderService.saveOrUpdate(goodsorder);//更新订单信息
        return true;
    }

}
